package com.example.myretrofit2.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myretrofit2.Goods;
import com.example.myretrofit2.R;
import com.example.myretrofit2.common.MyApplication;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.List;

public class GoodsListAdapter extends RecyclerView.Adapter<GoodsListAdapter.MyHolder> implements View.OnClickListener{
    Context context;
    List<Goods> list;
    OnitemGoodsClickLinsener onitemGoodsClickLinsener;

    public void setLinsener(OnitemGoodsClickLinsener onitemGoodsClickLinsener) {
        this.onitemGoodsClickLinsener = onitemGoodsClickLinsener;
    }

    public GoodsListAdapter(Context context, List<Goods> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view=View.inflate(context, R.layout.goods_list,null);
        MyHolder myHolder = new MyHolder(view);
        view.setOnClickListener(this);
        return myHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull MyHolder holder, int position) {
        holder.goodsName.setText(list.get(position).getGoodname());
        holder.goodsPrice.setText("￥"+list.get(position).getPrice());
        ImageLoader.getInstance().displayImage(MyApplication.imageUrl+list.get(position).getSrc(),holder.imageView);
        holder.itemView.setTag(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    @Override
    public void onClick(View view) {
        if(onitemGoodsClickLinsener != null){
            Goods goods = (Goods) view.getTag();
            onitemGoodsClickLinsener.onItemOrderClick(goods);
        }
    }

    public class MyHolder extends RecyclerView.ViewHolder{
        ImageView imageView;
        TextView goodsName;
        TextView goodsPrice;
        public MyHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.goods_img);
            goodsName = itemView.findViewById(R.id.goods_name);
            goodsPrice = itemView.findViewById(R.id.goods_price);
        }
    }
}
